package com.acme.bankapp.service.bank;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.StringTokenizer;

import com.acme.bankapp.domain.account.AbstractAccount;
import com.acme.bankapp.domain.account.AccountType;
import com.acme.bankapp.domain.account.CheckingAccount;
import com.acme.bankapp.domain.account.SavingAccount;
import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Client;

public class BankDataLoader {
	private static Client toClient(String st) {
		StringTokenizer sttoken = new StringTokenizer(st, "=;");
		Client cl = new Client();
		AbstractAccount ac;
		double balance;
		double overdraft;
		sttoken.nextToken();
		if (sttoken.nextToken().equals("c")) {
			sttoken.nextToken();
			balance = Double.parseDouble(sttoken.nextToken());
			sttoken.nextToken();
			overdraft = Double.parseDouble(sttoken.nextToken());
			ac = new CheckingAccount(AccountID.set(), balance, overdraft);
			cl.addAcc(ac);
		}

		else {
			sttoken.nextToken();
			balance = Double.parseDouble(sttoken.nextToken());
			ac = new SavingAccount(AccountID.set(), balance);
			cl.addAcc(ac);
		}

		sttoken.nextToken();
		cl.setName(sttoken.nextToken());
		sttoken.nextToken();
		if (sttoken.nextToken().equals("m")) {
			cl.setGen(Gender.MALE);
		} else {
			cl.setGen(Gender.FEMALE);
		}
		return cl;
	}

	public static void load(final Bank bank,File fpath) {
		if (!fpath.exists()) {
			System.out.println("File not Found");
			System.out.println(fpath.getAbsolutePath());
			return;
		}
		Client cl;
		try {
			RandomAccessFile r = new RandomAccessFile(fpath, "r");
			String st;
			do {
				st = r.readLine();
				if (st != null) {
					cl = BankDataLoader.toClient(st);
					bank.addclient(cl);
				}
			} while (st != null);
			r.close();
		} catch (IOException w) {

		}

	}

	public static void appendClientToFile(File path, Client cl) {
		FileOutputStream out;
		DataOutputStream datas;
		try {
			out = new FileOutputStream(path, true);
			datas = new DataOutputStream(out);
			StringBuilder builds = new StringBuilder();
			if (cl.getAcc().getAccountType() == AccountType.CHECKING) {
				builds.append("accounttype=c;");
				builds.append("balance=" + cl.getAcc().getBalance() + ";");
				builds.append("overdraft=" + cl.getAcc().getOverdraft()+";");
			} else {
				builds.append("accounttype=s;");
				builds.append("balance=" + cl.getAcc().getBalance()+";");
			}
			builds.append("name=" + cl.getName() + ";");
			if (cl.getGen() == Gender.MALE) {
				builds.append("gender=m\n");
			} else {
				builds.append("gender=f;\n");
			}
			datas.writeBytes(builds.toString());
			datas.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
